import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fsharing/core/models/store_apply_query.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class StoreApplyModel extends ViewModel {
  final Api api;
  String name;
  File _logo;
  File _idCard;
  File _license;
  String _errorMessage;
  StoreApplyQuery _data;

  StoreApplyModel(this.api) : super();

  File get logo => _logo;

  set logo(File value) {
    _logo = value;
    notifyListeners();
  }

  File get idCard => _idCard;

  set idCard(File value) {
    _idCard = value;
    notifyListeners();
  }

  File get license => _license;

  set license(File value) {
    _license = value;
    notifyListeners();
  }

  String get errorMessage => _errorMessage;

  StoreApplyQuery get data => _data;

  Future<ViewState> storeApplyStd(StoreApplyQuery lastStoreApplyQuery) async {
    viewState = ViewState.busy;
    try {
      // 在审核中，不能再次提交
      if (lastStoreApplyQuery.auditStatus == 'AUDITING') {
        throw '在审核中，不能再次提交';
      }
      // 如果没有ID，表示首次申请店铺
      if (lastStoreApplyQuery.id == null) {
        if (name == null || name.isEmpty) {
          throw '请输入店铺名称';
        }
        if (idCard == null) {
          throw '请选择身份证照片';
        }
        if (license == null) {
          throw '请选择营业执照';
        }
      }
      final params = <String, dynamic>{};
      params['id'] = lastStoreApplyQuery.id;
      params['name'] = name;
      params['logoFile'] = logo;
      params['idCardFile'] = idCard;
      params['licenseFile'] = license;
      _data = await api.storeApplyStd(params, cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
